Page({
  data: {
    // 初始头像和昵称，实际项目中通常从缓存或接口获取
    nickname: '',
    imgBaseUrl:'',
    avatarUrl:''
  },
  onLoad() {
    const app = getApp();
    if (app.globalData.imgBaseUrl) {
      const imgBaseUrl = app.globalData.imgBaseUrl;
      this.setData({
        imgBaseUrl: imgBaseUrl
      });
      console.log(imgBaseUrl);
    } else {
      console.error("错误：未获取到 imgBaseUrl");
    }
    var userinfo=wx.getStorageSync('userInfo');
    this.setData({avatarUrl:userinfo.avatarUrl,nickname:userinfo.nickname});
  },
  changeAvatar:function(e){
    var linkAvatar=e.detail.avatarUrl;
    this.setData({avatarUrl:linkAvatar});
  },
  // 返回上一页
  navigateBack: function() {
    wx.navigateBack({
      delta: 1
    });
  },
  // 处理输入事件：实时更新nickname数据
  onNicknameInput(e) {
    // e.detail.value 是输入框的当前值
    console.log(e);
    this.setData({
      nickname: e.detail.value
    });
  },
  saveProfile: function() {
    if (this.data.nickname===null&&this.data.nickname!=="请输入昵称") {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 显示保存中提示
    wx.showLoading({
      title: '保存中...',
      mask: true
    });

    // 模拟保存到服务器，实际项目中应该调用接口
    setTimeout(() => {
      // 保存到本地缓存
      const userInfo = {
        avatarUrl: this.data.avatarUrl,
        nickname: this.data.nickname
      };
      wx.setStorageSync('userInfo', userInfo);

      // 隐藏加载提示
      wx.hideLoading();

      // 显示保存成功提示
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1500
      });

      // 延迟返回上一页，让用户看到成功提示
      setTimeout(() => {
        this.navigateBack();
      }, 1500);
    }, 1000);
  }
});
